package JAVA300.第十章IO;

import java.io.*;

/**
 * 学习处理流之-数据流
 */

public class IO_Study14_ObjectInputStream {
    public static void main(String[] args) {

        //写出---序列化
     //   ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = null;
        try {
      //      objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(baos));//写到字节数组里
            objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("IO_Study13.txt")));//写到文件里

            objectOutputStream.writeUTF("hqqQYH");
            objectOutputStream.writeInt(18);
            objectOutputStream.writeChar('q');
            objectOutputStream.writeObject("hausdgiuasgd");//string等本身就实现了serializable接口

            objectOutputStream.writeObject(new Emloyee("hqq",20));


            objectOutputStream.flush();
            objectOutputStream.close();////写到文件里要关闭

           // byte[] datas = baos.toByteArray();
           // System.out.println(datas.length);//可以计算出占用字节

            //读取--反序列化
         //   ObjectInputStream ois  = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
            ObjectInputStream ois  = new ObjectInputStream(new BufferedInputStream(new FileInputStream("IO_Study13.txt")));//文件里反序列化
            String msg = ois.readUTF();
            int msg1 = ois.readInt();
            char msg2 = ois.readChar();

            Object str = ois.readObject();
            Object emloyee = ois.readObject();

            if (str instanceof String){//避免转换错误，因此加判断语句
                String msg3 = (String)str;//强转输出
                System.out.println(msg3);

            }
            if (emloyee instanceof Emloyee){//避免转换错误，因此加判断语句
                Emloyee emp = (Emloyee)emloyee;//强转输出
                System.out.println(emp.getAge());

            }
            System.out.println(msg);

            ois.close();//文件流释放资源
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

//自定义类 javabean
class  Emloyee implements Serializable{
    private String name;
    private int age;

    public Emloyee() {
    }

    public Emloyee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
